# -*- coding: utf-8 -*-
import hashlib
import json
import random
import string
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'zyf4010012520': {  # 离线付 云闪付 2% 10-5000
        'API_KEY': '007eef4599244a7f89974c1284f1bb65',
        'gateway': 'http://api.3721sz.com/api/anypay/sdk/v1/trade/pre/create',
        'query_gateway': 'http://api.3721sz.com/api/anypay/sdk/v1/trade/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_service_type(mch_id):
    return APP_CONF[mch_id]['service']


def _get_pay_type(service):
    if service == 'wechat':
        return '1001'
    elif service == 'alipay_red_packet': # 支付宝红包
        return '2001'
    elif service == 'alipay': # 支付宝转卡
        return '3001'
    elif service == 'unionpay':
        return '4001'
    return '4001'


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s = s + 'key=' + str(key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("ffpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    """ 创建订单 """
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('appId', app_id),
        ('payMethod', _get_pay_type(service)),
        ('notifyUrl', '{}/pay/api/{}/lixianfupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('returnUrl', '{}/pay/api/{}/lixianfupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('orderId', str(pay.id)),
        ('signType', 'MD5'),
        ('price', '%.2f' % pay_amount),
        ('nonceStr', ''.join(random.sample(string.ascii_letters + string.digits, 8))),
        ('timestamp', int(round(time.time() * 1000))),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("lixianfupay create data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=5)
    _LOGGER.info("lixianfupay create  response: %s", response.text)
    verify_sign(json.loads(response.text), api_key)
    return {'charge_info': json.loads(response.text)['result']}


# SUCCESS
def check_notify_sign(request, app_id):
    data = json.loads(request.body)
    api_key = _get_api_key(app_id)
    _LOGGER.info("lixianfupay notify data: %s, order_id is: %s", data, data['orderId'])
    verify_sign(data, api_key)
    pay_id = data['orderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('lixianfupay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('lixianfupay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['msg'])
    trade_no = str(data['tradeNo'])
    total_fee = float(data['price'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success' and total_fee > 0.0:
        _LOGGER.info('lixianfupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('appId', app_id),
        ('orderNo', pay_order.third_id),
        ('nonceStr', ''.join(random.sample(string.ascii_letters + string.digits, 8))),
        ('timestamp', int(round(time.time() * 1000))),
        ('signType', 'MD5'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("lixianfupay query data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=3)
    _LOGGER.info("lixianfupay query  rsp data: %s", response.text)
    verify_sign(json.loads(response.text), api_key)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['tradeStatus'])
        trade_no = str(data['orderNo'])
        total_fee = float(data['realAmount'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 10：支付中 20：通知中 30：成功 40：关闭
        if trade_status == '30':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('lixianfupay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('lixianfupay data error, status_code: %s', response.status_code)
